package com.dss.code_generation.controller;

import com.dss.code_generation.service.ITablesService;
import com.dss.code_generation.util.Result;
import com.dss.code_generation.util.StringUtils;
import com.dss.code_generation.vo.TablesVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.util.List;

/**
 * @Description: 表设计
 * @author: dongshoushan
 * @date: 2023年03月28日 15:46
 */
@RestController
@RequestMapping("/tableDesign")
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Api(tags ="99: 表设计")
public class TableDesignController {
    private final ITablesService tablesService;
    private final HttpServletResponse response;


    @GetMapping("/exportTableStructureExcelData")
    @ApiOperation(value = "查询需要导出excel的表", notes="查询需要导出excel的表")
    public Result exportTableStructureExcelData(){
        List<TablesVo> list = tablesService.exportTableStructureExcelData();
        return Result.success(list);
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出mysql表设计", notes = "导出mysql表设计")
    public void exportExcel(String tableName) throws Exception {
        tablesService.exportExcelTask(tableName);
    }
    @PostMapping("/deleteOtherTable")
    @ApiOperation(value = "删除其他表", notes = "删除其他表")
    public Result deleteOtherTable() {
        return Result.success(StringUtils.format("本次删除其他表：{}个",tablesService.deleteOtherTable()));
    }
    @PostMapping("/test")
    public void test() throws Exception {
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet();
        int k = 1;
        for (int i = 0; i < 40; i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j < 4; j++) {
                CellStyle style = wb.createCellStyle();

                style.setFillForegroundColor((short)(k));
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                Cell cell = row.createCell(j);
                cell.setCellValue(k);
                cell.setCellStyle(style);
                k++;
            }
        }
        // 写入文件
        FileOutputStream out = new FileOutputStream("aa.xlsx");
        wb.write(out);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition",
                "attachment;filename=" + java.net.URLEncoder.encode("mysql表设计导出.xlsx", "UTF-8"));
        response.flushBuffer();
        wb.write(response.getOutputStream());
    }
}
